import path from 'node:path'
import fs from 'node:fs/promises'
import { select, Separator, input } from '@inquirer/prompts'
import chalk from 'chalk'



const viewsPath = path.resolve(process.cwd(), './src/views')
const templatePath = path.resolve(process.cwd(), './src/template')


const genFolder = async (folders) => {
  const r1 = await input({
    message: '请输入菜单名称'
  })

  if (folders.includes(r1)) {
    console.log(chalk.red('该目录已存在，请确认'))
    bootstrap()
    return []
  }
  const r2 = await input({
    message: '请输入子菜单名称'
  })
  return [r1, r2]
}

const selectSubFolder = async (folderPath) => {
  const p = path.resolve(viewsPath, folderPath)
  const folders = await fs.readdir(p)
  const r1 = await input({
    message: '请输入子菜单名称'
  })
  if (folders.includes(r1)) {
    console.log(chalk.red('该子菜单已存在，请重新输入'))
    return selectSubFolder(folderPath)
  }
  return [r1]
}

const generateTemplate = async (dir) => {
  const dirPath = path.resolve(viewsPath, dir)
  try {
    await fs.mkdir(dirPath, { recursive: true })
  } catch (error) {
    console.log(chalk.red('目录创建失败'))
    console.error(error.message)
    return
  }
  try {
    console.log(templatePath)

    await fs.cp(templatePath, dirPath, { recursive: true })
    console.log(chalk.green('模板创建成功'))
  } catch (error) {
    console.log(error.message)
    console.log(chalk.green('模板创建失败'))

  }
}


const bootstrap = async () => {
  const folders = await fs.readdir(viewsPath)
  const path = []
  const p1 = await select({
    message: '请选择目录',
    choices: [
      ...folders.map((item) => ({
        value: item
      })),
      new Separator(),
      {
        value: 'new',
        name: '没有就新建一个吧'
      }
    ]
  })
  if (p1 === 'new') {
    const result = await genFolder(folders)
    if (!result.length) return
    path.push(...result)
  } else {
    const result = await selectSubFolder(p1)
    path.push(p1, ...result)
  }
  generateTemplate(path.join('/'))
}


bootstrap()